package org.gl.training.planner.dao;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.gl.training.planner.model.User;

@Stateless
public class UserDaoImpl implements UserDao {

	@PersistenceContext(unitName = "dailyPlannerPU")
	private EntityManager entityManager;

	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}

	@SuppressWarnings("unchecked")
	@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
	public User getUser(String username) {
		if (username == null) {
			return null;
		}

		Query query = entityManager
				.createQuery("select distinct u from User u join fetch u.userTypesList where u.userName=:userName");
		query.setParameter("userName", username);

		List<User> userList = query.getResultList();

		if (userList.size() == 1) {
			return userList.get(0);
		}

		return null;
	}

	public void save(User user) {
		entityManager.merge(user);
	}

	@SuppressWarnings("unchecked")
	@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
	public List<User> getUsers() {
		Query query = entityManager
				.createQuery("select distinct u from User u join fetch u.userTypesList");
		List<User> queryList = query.getResultList();
		return removeAdmins(queryList);
	}

	protected List<User> removeAdmins(List<User> originalList) {
		List<User> userList = new ArrayList<User>();
		for (User user : originalList) {
			if (!user.isAdmin()) {
				userList.add(user);
			}
		}
		return userList;
	}

	@Override
	@TransactionAttribute(TransactionAttributeType.REQUIRED)
	public void delete(User user) {
		User deleteUser = entityManager.find(User.class, user.getId());
		entityManager.remove(deleteUser);
	}

	@Override
	@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
	public User find(Integer id) {
		return entityManager.find(User.class, id);
	}

	@Override
	@TransactionAttribute(TransactionAttributeType.REQUIRED)
	public void delete(Integer userId) {
		User deleteUser = entityManager.find(User.class, userId);
		entityManager.remove(deleteUser);
	}
}
